<?php


namespace app\api\controller\lottery;


use app\api\controller\Controller;
use app\api\model\lottery\Action as ActionModel;
use app\api\model\lottery\Log as LotteryLogModel;
use app\api\model\user\LotteryLog as UserLotteryLogModel;
use think\Db;

/**
 * 抽奖
 */
class Action extends Controller
{
    /**
     * 抽奖活动
     */
    public function lists()
    {
        $actions = ActionModel::getGoingAction();
        return $actions ? $this->renderSuccess(compact('actions')) : $this->renderError('暂无可抽奖活动');
    }

    /**
     * 抽奖页面
     */
    public function read($lottery_id, ActionModel $actionModel)
    {
        $user = $this->getUser();
        $lottery = $actionModel->getActionById($lottery_id);
        if (!$lottery) {
            return $this->renderError('抽奖活动已结束');
        }
        $lottery['points'] = $user->points;
        //我的中奖记录
        $userLog = LotteryLogModel::getUserLog($user->user_id, $lottery_id);
        //抽奖剩余次数
        $lastCount = UserLotteryLogModel::lastLotteryCount($user->user_id, $lottery);
        $lottery['last_count'] = $lastCount;
        return $this->renderSuccess(compact('lottery', 'userLog'));
    }

    /**
     * 抽奖
     */
    public function check($lottery_id, ActionModel $actionModel)
    {
        $goods = $actionModel->click($lottery_id, $this->getUser());
        return $goods ? $this->renderSuccess(compact('goods')) : $this->renderError($actionModel->getError() ?: '抽奖失败，请联系管理与');
    }
}